home *** CD-ROM | disk | FTP | other *** search
/ Delphi Magazine Collection 2001 / Delphi Magazine Collection 20001 (2001).iso / DISKS / Issue43 / alfresco / AASelect.pas next >
Encoding:
Pascal/Delphi Source File  |  1999-01-24  |  2.0 KB  |  60 lines

  1. {*********************************************************}
  2. {* AASelect                                              *}
  3. {* Copyright (c) Julian M Bucknall 1998,1999             *}
  4. {* All rights reserved.                                  *}
  5. {*********************************************************}
  6. {* Random selection from an array / shuffling            *}
  7. {* Version 2                                             *}
  8. {*********************************************************}
  9.  
  10. {Note: this unit is released as freeware. In other words, you are free
  11.        to use this unit in your own applications, however I retain all
  12.        copyright to the code. JMB}
  13.  
  14. unit AASelect;
  15.  
  16. interface
  17.  
  18. procedure Shuffle(var aArray; aItemCount : integer; aItemSize : integer);
  19.   {-Random shuffle aItemCount items of size aItemSize in array aArray}
  20.  
  21. implementation
  22.  
  23. uses
  24.   SysUtils;
  25.  
  26. procedure Shuffle(var aArray; aItemCount : integer; aItemSize : integer);
  27. var
  28.   Inx      : integer;
  29.   RandInx  : integer;
  30.   SwapItem : PByteArray;
  31.   A        : TByteArray absolute aArray;
  32. begin
  33.   {if the number of items is 0 or 1, there's nothing to do: a shuffle
  34.    would reproduce the status quo}
  35.   if (aItemCount > 1) then begin
  36.     {get an item off the heap so that we can swap items in the array}
  37.     GetMem(SwapItem, aItemSize);
  38.     try
  39.       {for each element, counting from the right..,.}
  40.       for Inx := (aItemCount - 1) downto 1 do begin
  41.         {generate a random number from 0 to the index of the element
  42.          we've currently at}
  43.         RandInx := Random(Inx+1);
  44.         {if the random index does not equal our index, swap the items}
  45.         if (RandInx <> Inx) then begin
  46.           Move(A[Inx*aItemSize], SwapItem^, aItemSize);
  47.           Move(A[RandInx*aItemSize], A[Inx*aItemSize], aItemSize);
  48.           Move(SwapItem^, A[RandInx*aItemSize], aItemSize);
  49.         end;
  50.       end;
  51.     finally
  52.       {free the swap item}
  53.       FreeMem(SwapItem, aItemSize);
  54.     end;
  55.   end;
  56. end;
  57.  
  58.  
  59. end.
  60.